package com.blog.serlvet;

import com.alibaba.fastjson.JSONObject;
import com.blog.bean.BaseResponse;
import com.blog.bean.User;
import com.blog.dao.BlogDao;
import com.blog.dao.CommentDao;
import com.blog.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

public class CommentServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = LoginUtil.checkApiLogin(session, resp);
        if (user == null) {
            return;
        }

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        Integer blogId = null;
        try {
            blogId = Integer.valueOf(req.getParameter("id"));
            if (blogId == null) {
                writer.println(JSONObject.toJSONString(new BaseResponse(400, "评论失败", null)));
                return;
            }
        } catch (Exception e) {
            writer.println(JSONObject.toJSONString(new BaseResponse(400, "评论失败", null)));
            return;
        }

        String content = req.getParameter("content");
        if (content == null
                || content.length() < 1
                || content.length() > 500) {
            writer.println(JSONObject.toJSONString(new BaseResponse(400, "评论内容不正确", null)));
            return;
        }

        CommentDao commentDao = new CommentDao();
        BlogDao blogDao = new BlogDao();
        try {
            commentDao.publishComment(blogId, user.getId(), content);
            // 给微博评论数 +1
            blogDao.comment(blogId);
            writer.println(JSONObject.toJSONString(new BaseResponse(200, "评论发送成功", null)));
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(500);
        }
    }
}
